"""
分析结果API接口
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from sqlalchemy import func
from pydantic import BaseModel, Field
from typing import Dict, Any, List, Optional
from datetime import datetime

from core.database import get_db
from core.logging_config import get_logger, log_api_request
from core.auth import get_current_active_user, require_permission
from models.analysis_task import AnalysisTask, TaskStatus
from models.user import User

# 路由器
analysis_results_router = APIRouter(tags=["分析结果"])

# 日志记录器
logger = get_logger("analysis_results_api")


class AnalysisResultFilter(BaseModel):
    """分析结果过滤器"""
    task_id: Optional[int] = Field(None, description="任务ID")
    status: Optional[str] = Field(None, description="状态")
    start_date: Optional[datetime] = Field(None, description="开始日期")
    end_date: Optional[datetime] = Field(None, description="结束日期")
    pollution_type: Optional[str] = Field(None, description="污染类型")
    region: Optional[str] = Field(None, description="区域")
    min_confidence: Optional[float] = Field(None, ge=0, le=1, description="最小置信度")


class ReviewRequest(BaseModel):
    """审核请求"""
    status: str = Field(..., description="审核状态：approved, rejected")
    comments: Optional[str] = Field(None, description="审核意见")


@analysis_results_router.get("/")
@log_api_request("list_analysis_results")
@require_permission("analysis_result:view")
async def list_analysis_results(
    task_id: Optional[int] = Query(None, description="任务ID"),
    status: Optional[str] = Query(None, description="状态"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取分析结果列表"""
    logger.info("获取分析结果列表请求")
    
    try:
        # 构建查询
        query = db.query(AnalysisResult).join(PetitionData)
        
        # 应用过滤器
        if task_id:
            query = query.filter(AnalysisResult.task_id == task_id)
        if status:
            query = query.filter(AnalysisResult.status == status)
        
        # 计算总数
        total = query.count()
        
        # 分页查询
        results = query.order_by(AnalysisResult.created_at.desc()).offset(
            (page - 1) * page_size
        ).limit(page_size).all()
        
        # 转换为响应格式
        result_list = []
        for result in results:
            result_dict = result.to_dict()
            result_dict["petition_data"] = result.petition_data.to_dict() if result.petition_data else None
            result_list.append(result_dict)
        
        return {
            "total": total,
            "page": page,
            "page_size": page_size,
            "items": result_list,
            "total_pages": (total + page_size - 1) // page_size
        }
        
    except Exception as e:
        logger.error(f"获取分析结果列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@analysis_results_router.get("/{result_id}")
@log_api_request("get_analysis_result")
@require_permission("analysis_result:view")
async def get_analysis_result(
    result_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取分析结果详情"""
    logger.info(f"获取分析结果详情请求: {result_id}")
    
    try:
        result = db.query(AnalysisResult).filter(AnalysisResult.id == result_id).first()
        
        if not result:
            raise HTTPException(status_code=404, detail="分析结果不存在")
        
        result_dict = result.to_dict()
        result_dict["petition_data"] = result.petition_data.to_dict() if result.petition_data else None
        result_dict["task"] = result.task.to_dict() if result.task else None
        result_dict["reviewer"] = result.reviewer.to_dict() if result.reviewer else None
        
        return result_dict
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取分析结果详情失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@analysis_results_router.put("/{result_id}/review")
@log_api_request("review_analysis_result")
@require_permission("analysis_result:review")
async def review_analysis_result(
    result_id: int,
    request: ReviewRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """审核分析结果"""
    logger.info(f"审核分析结果请求: {result_id}")
    
    try:
        result = db.query(AnalysisResult).filter(AnalysisResult.id == result_id).first()
        
        if not result:
            raise HTTPException(status_code=404, detail="分析结果不存在")
        
        # 检查状态是否允许审核
        if result.status not in [ResultStatus.COMPLETED, ResultStatus.REVIEWED]:
            raise HTTPException(status_code=400, detail="只能审核已完成或已审核的结果")
        
        # 更新审核状态
        if request.status == "approved":
            result.approve_result(current_user.id, request.comments)
        elif request.status == "rejected":
            result.reject_result(current_user.id, request.comments)
        else:
            raise HTTPException(status_code=400, detail="无效的审核状态")
        
        db.commit()
        db.refresh(result)
        
        return {
            "message": "审核完成",
            "result_id": result.id,
            "status": result.status,
            "reviewer": current_user.username,
            "review_time": result.review_time
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"审核分析结果失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@analysis_results_router.get("/export/{format}")
@log_api_request("export_analysis_results")
@require_permission("analysis_result:export")
async def export_analysis_results(
    format: str,
    task_id: Optional[int] = Query(None, description="任务ID"),
    status: Optional[str] = Query(None, description="状态"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """导出分析结果"""
    logger.info(f"导出分析结果请求，格式: {format}")
    
    try:
        # 构建查询
        query = db.query(AnalysisResult).join(PetitionData)
        
        if task_id:
            query = query.filter(AnalysisResult.task_id == task_id)
        if status:
            query = query.filter(AnalysisResult.status == status)
        
        results = query.all()
        
        if format == "json":
            export_data = {
                "export_info": {
                    "format": "json",
                    "exported_at": datetime.now().isoformat(),
                    "total_count": len(results),
                    "exported_by": current_user.username
                },
                "results": [
                    {
                        "id": result.id,
                        "petition_id": result.petition_data.petition_id if result.petition_data else None,
                        "title": result.petition_data.title if result.petition_data else None,
                        "status": result.status,
                        "confidence_score": result.confidence_score,
                        "extracted_info": result.extracted_info,
                        "pollution_type": result.pollution_type,
                        "sentiment_analysis": result.sentiment_analysis,
                        "created_at": result.created_at.isoformat(),
                        "reviewed_at": result.review_time.isoformat() if result.review_time else None
                    }
                    for result in results
                ]
            }
            
            return export_data
        
        elif format == "csv":
            # 这里可以实现CSV导出逻辑
            return {"message": "CSV导出功能待实现"}
        
        else:
            raise HTTPException(status_code=400, detail="不支持的导出格式")
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"导出分析结果失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@analysis_results_router.get("/statistics/summary")
@log_api_request("analysis_results_summary")
@require_permission("analysis_result:view")
async def get_analysis_results_summary(
    task_id: Optional[int] = Query(None, description="任务ID"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取分析结果统计摘要"""
    logger.info("获取分析结果统计摘要请求")
    
    try:
        query = db.query(AnalysisResult)
        
        if task_id:
            query = query.filter(AnalysisResult.task_id == task_id)
        
        # 基础统计
        total_results = query.count()
        
        # 按状态统计
        status_stats = db.query(
            AnalysisResult.status,
            func.count(AnalysisResult.id).label('count')
        ).filter(AnalysisResult.task_id == task_id if task_id else True).group_by(
            AnalysisResult.status
        ).all()
        
        # 置信度统计
        confidence_stats = db.query(
            func.avg(AnalysisResult.confidence_score).label('avg_confidence'),
            func.min(AnalysisResult.confidence_score).label('min_confidence'),
            func.max(AnalysisResult.confidence_score).label('max_confidence')
        ).filter(
            AnalysisResult.confidence_score.isnot(None),
            AnalysisResult.task_id == task_id if task_id else True
        ).first()
        
        # 今日统计
        today = datetime.now().date()
        today_results = query.filter(
            func.date(AnalysisResult.created_at) == today
        ).count()
        
        return {
            "total_results": total_results,
            "today_results": today_results,
            "status_distribution": [
                {"status": stat.status, "count": stat.count}
                for stat in status_stats
            ],
            "confidence_stats": {
                "average": round(confidence_stats.avg_confidence, 3) if confidence_stats.avg_confidence else 0,
                "min": confidence_stats.min_confidence,
                "max": confidence_stats.max_confidence
            } if confidence_stats.avg_confidence else None
        }
        
    except Exception as e:
        logger.error(f"获取分析结果统计摘要失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))